package com.gexin.controller.system.weixin;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.gexin.common.model.ApiResponse;
import com.gexin.core.web.SystemBaseController;
import com.gexin.model.weixin.WeixinAppConfig;
import com.gexin.model.weixin.WxMenu;
import com.gexin.weixin.kit.WxConfigKit;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;
import org.apache.commons.lang3.StringUtils;

/**
 *  微信app配置
 * @author W.cl
 *  
 */
@ControllerBind(controllerKey = "/system/weixin/appconfig", viewPath = "WEB-INF/system/weixin/")
public class WeiXinAppConfigController extends SystemBaseController {

	private  static final Log log =Log.getLog(WeiXinAppConfigController.class);

	//首页
	public void index(){
		render("wx_app_config_list.html");
	}
	
	public void query(){
		WeixinAppConfig wxAppConfig = new WeixinAppConfig();
		wxAppConfig.setAppTitle(getPara("app_title"));
		renderJson(WeixinAppConfig.dao.paginate(getpage(), getpageSize(),wxAppConfig));
	}
	
	
	public void add_edit() {
		setAttr("id",getPara(0,null));
		setAttr("cfg", WeixinAppConfig.dao.findById(getPara(0)));
		List<WxMenu> parentMenu=WxMenu.dao.getParentMenuByShopId(getParaToInt(0));
		for (int i = 0; i < parentMenu.size(); i++) {
			List<WxMenu> childMenu=WxMenu.dao.getChildMenuByShopId(getParaToInt(0), parentMenu.get(i).getId());
			Map<String,List<WxMenu>> childMenus = new LinkedHashMap<String,List<WxMenu>>();
			childMenus.put("son",childMenu);
			parentMenu.get(i).put("item",childMenus);
		}
		setAttr("menu_list", JsonKit.toJson(parentMenu));
		render("wx_app_config_add_edit.html");
	}
	
	public void save(){
		WeixinAppConfig cfg = getModel(WeixinAppConfig.class,"cfg");
		cfg.setCreatetime(new Date());
		//判断状态
		if(cfg.getMessageEncrypt()==null){
			cfg.set("message_encrypt", 0);	
		}
		if(cfg.getId()==null){
			cfg.save();
		}else{
			//每次编辑完清除缓存
			cfg.update();
			WxConfigKit.clear_CacheById(cfg.getId());
		}
		redirect("/system/weixin/appconfig");
	}
	
	
	public void delete() {
		if (WeixinAppConfig.dao.deleteById(getPara(0))) {
			renderJson(new ApiResponse(true));
		}else {
			renderJson(new ApiResponse(false));
		}
	}



	/** 添加父菜单*/
	public void add_parentMenu() {
		String id=getPara("id");
		WeixinAppConfig auth =WeixinAppConfig.dao.findById(id);
		WxMenu menu=new WxMenu();
		menu.setConfigId(auth.getId());
		menu.setType("view");
		menu.setName(getPara("name"));
		menu.setUrl(getPara("url"));
		menu.setSort(getParaToInt("sort"));
		if (menu.save()) {
			success(menu);
		}else {
			fail("请稍后再试");
		}
	}
	/** 添加子菜单*/
	public void add_childMenu() {
		String id=getPara("id");
		WeixinAppConfig auth =WeixinAppConfig.dao.findById(id);
		WxMenu menu=new WxMenu();
		menu.setConfigId(auth.getId());
		menu.setType("view");
		menu.setName(getPara("name"));
		menu.setUrl(getPara("url"));
		menu.setSort(getParaToInt("sort"));
		menu.setPid(getParaToInt("pid"));
		WxMenu parentMenu=WxMenu.dao.findById(getPara("pid"));
		if (parentMenu.getType().equals("click")) {
			parentMenu.setType("view");
			parentMenu.update();
		}
		if (menu.save()) {
			success(menu);
		}else {
			fail("请稍后再试");
		}
	}
	/** 删除菜单*/
	public void del_menu(){
		String id=getPara("id");
		setAttr("id", id);
		WeixinAppConfig auth =WeixinAppConfig.dao.findById(id);
		WxMenu menu=WxMenu.dao.findById(getPara("menu_id"));
		if (menu.getPid()!=0) {
			if (WxMenu.dao.deleteById(getPara("menu_id"))) {
				success();
			}else {
				fail("请稍后再试");
			}
		}else {
			List<WxMenu> menu_list=WxMenu.dao.getChildMenuByShopId(auth.getId(), getParaToInt("menu_id"));
			for (int i = 0; i < menu_list.size(); i++) {
				if (WxMenu.dao.deleteById(menu_list.get(i).getId())){
					success();
				}else {
					fail("请稍后再试");
					return;
				}
			}
			if (WxMenu.dao.deleteById(getPara("menu_id"))) {
				success();
			}else {
				fail("请稍后再试");
			}
		}
	}
	/** 编辑菜单*/
	public void edit_menu(){
		WxMenu menu=WxMenu.dao.findById(getPara("menu_id"));
		if(menu==null || menu.getId()==null){
			menu=new WxMenu();
		}
		menu.setConfigId(getParaToInt("config_id"));
		menu.setName(getPara("name"));
		menu.setUrl(getPara("url"));
		String msg;
		if(menu.getId()==null){
			menu.save();
			msg="添加成功";
		}else {
			menu.update();
			msg="修改成功";
		}
		success(msg);
	}
	/** 发布菜单*/
	public void release_menu(){
		String id=getPara("id");
		WeixinAppConfig auth = WeixinAppConfig.dao.findById(Integer.valueOf(id));
		if(StringUtils.isEmpty(auth.getAppId())){
			fail("请先设置应用ID");
			return;
		}
		if(StringUtils.isEmpty(auth.getAppSecret())){
			fail("请先设置应用秘钥");
			return;
		}
		Map<String, List<WxMenu>> menu=new LinkedHashMap<String, List<WxMenu>>();
		List<WxMenu> parentMenu=WxMenu.dao.getParentMenu(auth.getId());
		for (int i = 0; i < parentMenu.size(); i++) {
			List<WxMenu> childMenu=WxMenu.dao.getChildMenu(auth.getId(), parentMenu.get(i).getId());
			if (childMenu.size()!=0) {
				parentMenu.get(i).put("sub_button",childMenu);
			}
			parentMenu.get(i).remove("id");
		}
		menu.put("button", parentMenu);
		String menu_json  = JsonKit.toJson(menu);
		ApiConfig apiConfig=WxConfigKit.getApiConfig(auth.getId());
		ApiConfigKit.setThreadLocalAppId(apiConfig.getAppId());
		ApiResult apiResult= MenuApi.createMenu(menu_json);
		log.info(auth.getId()+",总后台发布微信菜单结果:"+ JSON.toJSONString(apiResult));
		if (apiResult.isSucceed())
			success(apiResult.getJson());
		else
			fail(apiResult.getErrorMsg());
	}
	/** 系统链接*/
	public void url(){
		success();
	}


}


